package cn.ygkj.noticespringbootstarter.config;

import cn.ygkj.noticespringbootstarter.entity.NoticeConfig;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author : ☪lei☠
 * @ClassName : NoticeAutoconfiguration
 * @Description :
 * @createTime : 2022年07月24日 16:23:00
 */
@Configuration
@EnableConfigurationProperties(NoticeConfig.class)
public class NoticeAutoconfiguration {


    @Bean
    public DingTalkClient getDingTalkClient(NoticeConfig noticeConfig) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
       return new DefaultDingTalkClient(noticeConfig.getUrl() + sign(noticeConfig));
    }


    private  String sign(NoticeConfig p) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        Long timestamp = System.currentTimeMillis();
        String secret = p.getSecret();
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
        return "&timestamp=" + timestamp + "&sign=" + sign;
    }

}
